﻿#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct PersonCA
{
	char name[64];
	int age;
};
struct Teacher
{
	char* name;
	int age;
};
void testCA()
{
	struct PersonCA person1 = { "aaa",20 };
	struct PersonCA person2 = { "bbb",30 };

	//3.赋值操作；
	person2 = person1;

	printf("1.输出结构体变量person1的name：%s和age：%d\n", person1.name, person1.age);//aaa 20
	printf("2.输出结构体变量person2的name：%s和age：%d\n", person2.name, person2.age);//bbb 30 --> aaa 20

	struct Teacher teacher1;
	teacher1.name = malloc(sizeof(char) * 64);
	memset(teacher1.name, 0, 64);
	strcpy(teacher1.name, "ccc");
	teacher1.age = 40;

	struct Teacher teacher2;
	teacher2.name = malloc(sizeof(char) * 128);
	memset(teacher2.name, 0, 128);
	strcpy(teacher2.name, "ddddddddddddddddd");
	teacher2.age = 50;

	printf("8.输出结构体变量teacher1的内存大小：%d\n", sizeof(teacher1));//8
	printf("9.输出结构体变量teacher2的内存大小：%d\n", sizeof(teacher2));//8

	//7.赋值操作；teacher2.name指向teacher1.name，只是赋值了地址。后面释放内存时，造成同一内存空间释放两次，所以
		//程序直接报错；还会造成内存泄漏，因为teacher2.name原本的128个字节没有被释放，就直接泄漏了；主要还是结构
		//体成员指针变量char* name造成的；
	//teacher2 = teacher1;

	//10.不使用上面默认的结构体赋值行为；如果结构体内部有指针指向堆内存，那么就不能使用编译器默认的赋值行为，应
		//该手动控制赋值过程；
	if (teacher2.name != NULL)
	{
		free(teacher2.name);
		teacher2.name = NULL;
	}
	teacher2.name = malloc(strlen(teacher1.name) + 1);
	strcpy(teacher2.name, teacher1.name);
	teacher2.age = teacher1.age;
	//-----------------------------------------------------------------------------------------------


	printf("---------------------------------------------\n");
	printf("4.输出结构体变量teacher1的name：%s和age：%d\n", teacher1.name, teacher1.age);//ccc 40
	printf("5.输出结构体变量teacher2的name：%s和age：%d\n", teacher2.name, teacher2.age);//ddddddddddddddddd 50  -->  ccc 40

	//6.释放结构体变量teacher1.name的堆内存；
	if (teacher1.name != NULL)
	{
		free(teacher1.name);
		teacher1.name = NULL;
	}

	if (teacher2.name != NULL)
	{
		free(teacher2.name);
		teacher2.name = NULL;
	}

}

//main206：结构体赋值
int main206()
{
	testCA();

	system("pause");
	return EXIT_SUCCESS;
}